package com.android.powerbankpad.reflection;

import android.app.Activity;
import android.view.View;

import com.ws.universal.tools.utils.LogcatUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 实现
 */
public class MyOnclik {

    public static void injection(Activity activity) {
        //反射 activity
        Class<? extends Activity> activityClass = activity.getClass();

        //通过反射得到所有注解
        Annotation[] annotations = activityClass.getAnnotations();
        // a//nnotations
        for (Annotation annotation : annotations) {
            //获取注解上的注解
            Class<? extends Annotation> annotationType = annotation.annotationType();
            if (annotationType.isAnnotationPresent(EventType.class)) {
                //获取单个注解
                EventType eventType = annotationType.getAnnotation(EventType.class);
                String clickName = eventType.setOnclckName();
                Class clickLinstener = eventType.clickLinstener();
                try {
                    Method declaredMethod = annotationType.getDeclaredMethod("");
                    int[] findBuyId = (int[]) declaredMethod.invoke(annotationType);
                    Object proxyInstance = Proxy.newProxyInstance(activity.getClassLoader(), new Class[]{clickLinstener}, new InvocationHandler() {
                        @Override
                        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                            return method.invoke(activity,objects);
                        }
                    });
                    for (int id : findBuyId) {
                        View viewById = activity.findViewById(id);
                        Method declaredMethod1 = viewById.getClass().getDeclaredMethod(clickName, clickLinstener);
                        declaredMethod1.invoke(viewById, proxyInstance);
                    }
                } catch (Exception e) {
                    LogcatUtils.e(" injection " + e.getMessage());
                }

            }
        }
    }
}
